<?php
namespace app\api\controller;

use app\common\model\Clue as ClueModel;
use app\common\model\ClueErrorLog;
use think\Db;
use think\Queue;
use app\api\model\Clue as ApiClueModel;

class AcceptclueDae
{
    //我们系统RSA加密私钥
    const PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----
MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBAOuPjnF4MY7rXS6k
1bAXsmkT6V1TmzueMwSytzhp7DfabTMmtA7OHuJdIEjfH8J80ZkxUFo1iTdhnLBd
uwlCKT5Wy2lJWhkiHg10lhWTRMep/TzGaKCotvy5T4CJoram0WZc9iyTtUFKFaPf
tSuUBSLpeuliQMfY9uQU4rP/us8tAgMBAAECgYEAlRPxThaHJrAF9PMU2bDllGKp
mgrDf2OLXjnMgsNmX6K44VppMcV4/kF5oSS0cN2VuKHg/HZNNONtyqBHMoDQoBBq
yxBB5Zv5Jkh15DHZde+yR/6ALA3CEAidOffQbO1Z61rnr++tMplYBJK+seENVPji
byG9bwvtv8XwjvLG5PECQQD4+pFpUzqjpOTHMbg3pc12yhEkwY6Srb1igAD//C3L
oNM9lja6aGmmBSH6yo3sHEgJ6DUydZeoa7IczgqgxTS3AkEA8jQe75MwksZ4iUVg
P4PFe11Kr3PmOf6xtOR3x2hWpw3CRf6Ld8vgtfKlhy1MAtG7zQkJu6DqdaStEfo2
18afOwJBAJ6nBDvKVkZqz4GC1DFZjNiSIGR8lj4vScvXZ0u3RPNJsvG+o3cbC59I
DAQESHVY/Cqb9jIGLrKala+3N5yErXcCQQCIjTQn1C9dgQIyOmfyR0OOsuFJnClf
5yWfm/Of/EZmds5iEgnlp49wZXZHiRVCvaaJCaBwJWAqpYZiDVTgQH5DAkEAhaeo
oROUXbHG3J9ukoMyPIwpM8myRGTqb7LpcJ/jJ6CUNUYWlFNj9CaJay/fcKCKC+P7
Efn20UAqCA7+VVwwHw==
-----END PRIVATE KEY-----
";

    //我们系统RSA加密公钥
    const PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDrj45xeDGO610upNWwF7JpE+ld
U5s7njMEsrc4aew32m0zJrQOzh7iXSBI3x/CfNGZMVBaNYk3YZywXbsJQik+Vstp
SVoZIh4NdJYVk0THqf08xmigqLb8uU+AiaK2ptFmXPYsk7VBShWj37UrlAUi6Xrp
YkDH2PbkFOKz/7rPLQIDAQAB
-----END PUBLIC KEY-----
";

    //大鹅推 RSA加密公钥
    const DAE_PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDMGBoT8Kx41uOaRN7XPBHDkYN6qcrtYgWBipQgfQIOpeQO1Zf+enO3j6Xt7ey0W9HVCbMa69+mg2eZnR8a0R+xa9OE9AqWZKH4ug1mk6QDD32kLIVVq2WJ7yDL4tD2XqBbysDpp0o7rbCa3RJjEp8Lw2W++SAnzvDKPXcXc81thQIDAQAB
-----END PUBLIC KEY-----";

    //投放账号: 大鹅推
    const ACCOUNT_ID = 9518;

    private $public_key_resource = ''; //公密钥资源
    private $private_key_resource = ''; //私密钥资源

    //大鹅推
    public function push()
    {
        $post = \input('post.');

        if (empty($post) || empty($post['bizContent']) || empty($post['secretKey'])) {
            $ret = ["code" => "000016", 'msg' => '参数为空', 'dealStatus' => "9999", 'dealDesc' => "请求参数为空，参数bizContent、secretKey参数为空"];
            $this->sb_return(json_encode($ret, JSON_UNESCAPED_UNICODE));
        }
        //解密 返回数组
        $postData = $this->sb_get($post['secretKey'], $post['bizContent']);
        writelog("大鹅推请求 接收原参数:" . json_encode($post, JSON_UNESCAPED_UNICODE). ",解密后参数:". json_encode($postData, JSON_UNESCAPED_UNICODE), 'daepush');

        $aid = self::ACCOUNT_ID;
        $insertLog = [
            'api_url' => '大鹅推',
            'adv_id' => $aid,
            'phone' => isset($postData['phoneNo']) ? $postData['phoneNo'] : '',
            'name' => isset($postData['custName']) ? $postData['custName'] : '',
            'city' => isset($postData['addressCity']) ? $postData['addressCity'] : '',
            'param' => json_encode($_GET, JSON_UNESCAPED_UNICODE),
            'data' => json_encode($postData, JSON_UNESCAPED_UNICODE),
            'create_time' => date('Y-m-d H:i:s')
        ];
        $apiId = Db::name('clue_api_log')->insertGetId($insertLog);

        if (empty($postData['custName'])) {
            ApiClueModel::setClueApiLogError($apiId, '姓名不能为空');
            $ret = ["code" => "000004", 'msg' => '姓名不能为空', 'dealStatus' => "9999", 'dealDesc' => "姓名不能为空"];
            $this->sb_return(json_encode($ret, JSON_UNESCAPED_UNICODE));
        }

        if (empty($postData['phoneNo'])) {
            ApiClueModel::setClueApiLogError($apiId, '手机号不能为空');
            $ret = ["code" => "000004", 'msg' => '手机号不能为空', 'dealStatus' => "9999", 'dealDesc' => "手机号不能为空"];
            $this->sb_return(json_encode($ret, JSON_UNESCAPED_UNICODE));
        }

        if (empty($postData['addressCity'])) {
            ApiClueModel::setClueApiLogError($apiId, '城市不能为空');
            $ret = ["code" => "000004", 'msg' => '城市不能为空', 'dealStatus' => "9999", 'dealDesc' => "城市不能为空"];
            $this->sb_return(json_encode($ret, JSON_UNESCAPED_UNICODE));
        }

        // 车抵
        $pro_id = 4;

        //优先级：房>车>公积金
        //产品为公积金
        if (!empty($postData['housingFund']) && $postData['housingFund'] == 1) {
            $pro_id = 6;
        }

        //产品为车
        if (!empty($postData['car']) && $postData['car'] == 1) {
            $pro_id = 4;
        }

        //产品为房
        if (!empty($postData['house']) && $postData['house'] == 1) {
            $pro_id = 3;
        }

        $params['clue_id'] = create_no('DET');
        $params['adv_id'] = $aid;;
        $params['clue_name'] = $postData['custName'] ?? "";
        $params['phone'] = $postData['phoneNo'];
        $params['city'] = $postData['addressCity'];
        $params['apply_limit'] = isset($postData['limit']) ? $postData['limit'] : 0;
        $params['age'] = $postData['age'] ?? 0;
        $params['gender'] = !empty($postData['gender']) ? ($postData['gender'] == '01' ? 1 : 2) : 0;
        $params['pro_id'] = $pro_id;
        $params['ip'] = !empty($postData['custIp']) ? $postData['custIp'] : get_client_ip();

        $car = $house = $public_funds = $remark = [];
        //房
        if (isset($postData['houseDetail']) && !empty($postData['houseDetail'])) {
            if ($postData['houseDetail'] == 1) {
                $house = "商品房";
                $remark[] = ['房' => $house];
            } elseif ($postData['houseDetail'] == 2) {
                $house = "自建房";
                $remark[] = ['房' => $house];
            }
        }
        //车
        if (isset($postData['carDetail']) && !empty($postData['carDetail'])) {
            if ($postData['carDetail'] == 1) {
                $car = "未抵押车";
                $remark[] = ['车' => $car];
            } elseif ($postData['carDetail'] == 2) {
                $car = "抵押车";
                $remark[] = ['车' => $car];
            }
        }
        //公积金
        if (isset($postData['housingFundDetail']) && !empty($postData['housingFundDetail'])) {
            if ($postData['housingFundDetail'] == 1) {
                $public_funds = "公积金缴纳6个月以内";
                $remark[] = ['公积金' => $public_funds];
            } elseif ($postData['housingFundDetail'] == 2) {
                $public_funds = "公积金缴纳6个月以上";
                $remark[] = ['公积金' => $public_funds];
            }
        }

        // 详细信息 扩展字段
        if (!empty($postData['extraContent'])) {
            $extraContent = json_decode($postData['extraContent'], true);
            //  车辆信息
            if (!empty($extraContent['cardId'])) {
                $remark[] = ['车牌号' => $extraContent['cardId']];
            }
            if (!empty($extraContent['carMoney'])) {
                $remark[] = ['车辆价值' => $extraContent['carMoney']];
            }
        }

        $params['car'] = !empty($car) ? $car : "";
        $params['house'] = !empty($house) ? $house : "";
        $params['public_funds'] = !empty($public_funds) ? $public_funds : "";
        $params['remark'] = !empty($remark) ? json_encode($remark, JSON_UNESCAPED_UNICODE) : "";

        $isDayPhone = (new ClueModel())->isRepeatClue($params['phone'], $params['adv_id']);
        if ($isDayPhone) {
            ApiClueModel::setClueApiLogError($apiId, '线索已存在');
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索已存在', $params);
            //return Json(['msg' => '线索已存在', 'status' => 200, "code" => 202]);
            //$ret = ["code" => "000015", 'msg' => '线索已存在', 'dealStatus' => "9999", 'dealDesc' => "线索已存在"];
            $ret = ["code" => "000000", 'msg' => '线索接收成功', 'dealStatus' => "0000", 'dealDesc' => "线索接收成功"];
            $this->sb_return(json_encode($ret, JSON_UNESCAPED_UNICODE));
        }

        $isAid = Db::name('account')->where('adv_id', $aid)->find();
        if ($isAid['status'] != 1) {
            ApiClueModel::setClueApiLogError($apiId, '账户已禁用');
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户已禁用', $params);
            //return Json(['msg' => '账户已禁用', 'status' => 200, "code" => 500]);
            $ret = ["code" => "000015", 'msg' => '账户已禁用', 'dealStatus' => "9999", 'dealDesc' => "账户已禁用"];
            $this->sb_return(json_encode($ret, JSON_UNESCAPED_UNICODE));
        }
        $params['type'] = $isAid['channel_id'];

        $isBlack = model('clue')->where(['phone' => $params['phone'], 'is_black' => 1])->find();
        if ($isBlack) {
            ApiClueModel::setClueApiLogError($apiId, '黑名单线索');
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '黑名单线索', $params);
            //return Json(['msg' => '进线失败，黑名单线索', 'status' => 200, "code" => 500]);
            //$ret = ["code" => "000015", 'msg' => '进线失败，黑名单线索', 'dealStatus' => "9999", 'dealDesc' => "进线失败，黑名单线索"];
            $ret = ["code" => "000000", 'msg' => '线索接收成功', 'dealStatus' => "0000", 'dealDesc' => "线索接收成功"];
            $this->sb_return(json_encode($ret, JSON_UNESCAPED_UNICODE));
        }

        if (strpos($params['city'], '|') !== false) {
            $city_t = explode('|', $params['city']);
        } elseif (strpos($params['city'], '-') !== false) {
            $city_t = explode('-', $params['city']);
        } else {
            $city_t = [$params['city']];
        }

        $city_info = clue_city_transform($city_t);

        if (!$city_info) {
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '未匹配到城市id', $params);
//            throw new ParamException(['msg'=>'线索接收失败，线索没有城市属性','errorCode'=>40001]);
            $params['city'] = '';
            $params['err_msg'] = '未匹配到城市id城市解析失败';
        } else {
            $province = Db::name('city')->where(['id' => $city_info['pid']])->find();
            $params['city'] = $province['id'] . '-' . $city_info['id'];
        }

        //城市是否禁用
        $isCity = model('accountCity')->where(['acc_id' => $isAid['id'], 'city' => $params['city'], 'status' => 1])->find();
        if (!empty($isCity)) {
            ApiClueModel::setClueApiLogError($apiId, '账户城市已禁用');
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市已禁用', $post);
            //return Json(['msg' => '账户城市已禁用', 'status' => 200, "code" => 500]);
            /*$ret = ["code" => 000015, 'msg' => '账户城市已禁用', 'dealStatus' => 9999, 'dealDesc' => "账户城市已禁用"];
            $this->sb_return(json_encode($ret, JSON_UNESCAPED_UNICODE));*/
            //$ret = ["code" => "000015", 'msg' => '线索已存在', 'dealStatus' => "9999", 'dealDesc' => "线索已存在"];
            $ret = ["code" => "000000", 'msg' => '线索接收成功', 'dealStatus' => "0000", 'dealDesc' => "线索接收成功"];
            $this->sb_return(json_encode($ret, JSON_UNESCAPED_UNICODE));
        }

        // 城市是否准入
        $is_allow = (new \app\common\model\Clue())->allowAccountCity($isAid['id'], $params['city']);
        if ($is_allow === false) {
            ApiClueModel::setClueApiLogError($apiId, '账户城市不准入');
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市不准入', $post);
            $ret = ["code" => "000000", 'msg' => '线索接收成功', 'dealStatus' => "0000", 'dealDesc' => "线索接收成功"];
            $this->sb_return(json_encode($ret, JSON_UNESCAPED_UNICODE));
        }

        $clueCost = model('ClueAddCost')
            ->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => $params['city']])
            ->where('status', 1)
            ->find();
        if (empty($clueCost)) {
            // 找不到城市就找默认全国城市
            $clueCost = model('ClueAddCost')
                ->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => ""])
                ->where('status', 1)
                ->find();
        }
        if (!empty($clueCost)) {
            $params['price'] = $clueCost['money'];
            $params['true_price'] = $clueCost['money'];
            $params['xz_price'] = $clueCost['money'];
            $params['xz_true_price'] = $clueCost['money'];
            $params['xz_price2'] = $clueCost['money'];
            $params['xz_true_price2'] = $clueCost['money'];
        } else {
            $params['price'] = $isAid['clue_cost'];
            $params['true_price'] = $isAid['clue_cost'];
            $params['xz_price'] = $isAid['clue_cost'];
            $params['xz_true_price'] = $isAid['clue_cost'];
            $params['xz_price2'] = $isAid['clue_cost'];
            $params['xz_true_price2'] = $isAid['clue_cost'];
        }
        $params['account_id'] = $isAid['id'];
        //判断线索重复
        $isClue = model('clue')->where(['phone' => $params['phone']])->find();

        // 1.记录线索
        $clueModel = new \app\common\model\Clue();
        $res = $clueModel->saveData($params);
        $id = $clueModel->id;

        if ($res['code'] != 1000) {
            ApiClueModel::setClueApiLogError($apiId, '线索接收失败');
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索接收失败', $post);
            //return Json(['msg' => '线索接收失败', 'status' => 200, "code" => 500]);
            $ret = ["code" => "000015", 'msg' => '线索接收失败', 'dealStatus' => "9999", 'dealDesc' => "线索接收失败"];
            $this->sb_return(json_encode($ret, JSON_UNESCAPED_UNICODE));
        }

        Db::name('clue_api_log')->where('id', $apiId)->update(['status' => 1]);

        if ($isClue) {
            Db::name('clue_err_log')->insert(['type' => 1, 'phone' => $params['phone'], 'clue_id' => $id, 'adv_id' => $params['adv_id'], 'pro_id' => $params['pro_id'], 'city' => $params['city'], 'create_time' => time()]);
        }

        if (empty($params['city'])) {
            //return Json(['status' => 200, 'msg' => '线索接收成功', 'code' => 200]);
            $ret = ["code" => "000000", 'msg' => '线索接收成功', 'dealStatus' => "0000", 'dealDesc' => "线索接收成功"];
            $this->sb_return(json_encode($ret, JSON_UNESCAPED_UNICODE));
        }

        if (strpos($params['clue_name'], '测试') !== false) {
            //return Json(['status' => 200, 'msg' => '测试线索接收成功', 'code' => 200]);
            $ret = ["code" => "000000", 'msg' => '测试线索接收成功', 'dealStatus' => "0000", 'dealDesc' => "测试线索接收成功"];
            $this->sb_return(json_encode($ret, JSON_UNESCAPED_UNICODE));
        }

        // 2.推送线索
//        $clue_info = $clueModel->find($id);
//
//        $res = $this->cluePush($clue_info, true);

        $jobHandlerClassName = 'app\job\ExprotClue@fire';
        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName = "ExprotClue";

        $jobData = ['id' => $id];

        Queue::push($jobHandlerClassName, $jobData, $jobQueueName);

        //return Json(['status' => 200, 'msg' => '线索接收成功', 'code' => 200]);
        $ret = ["code" => "000000", 'msg' => '线索接收成功', 'dealStatus' => "0000", 'dealDesc' => "线索接收成功"];
        $this->sb_return(json_encode($ret, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 架构函数
     * @param [string] $public_key  [对方公密钥文件地址]
     * @param [string] $private_key [己方私密钥文件地址]
     */
    private function setResource($public_key,$private_key) {
        $this->public_key_resource = openssl_pkey_get_public($public_key);
        $this->private_key_resource = openssl_pkey_get_private($private_key);
    }

    /**
     * 用私密钥加密
     */
    private function privateEncrypt($input) {
        openssl_private_encrypt($input,$output,$this->private_key_resource);
        return base64_encode($output);
    }
    /**
     * 解密 私密钥加密后的密文
     */
    private function publicDecrypt($input) {
        openssl_public_decrypt(base64_decode($input),$output,$this->public_key_resource);
        return $output;
    }
    /**
     * 用公密钥加密
     */
    private function publicEncrypt($input) {
        openssl_public_encrypt($input,$output,$this->public_key_resource);
        return base64_encode($output);
    }
    /**
     * 解密 公密钥加密后的密文
     */
    private function privateDecrypt($input) {
        openssl_private_decrypt(base64_decode($input),$output,$this->private_key_resource);
        return $output;
    }

    //给省呗加密返回
    private function sb_return($json_bizContent)
    {
        $this->setResource(self::DAE_PUBLIC_KEY, self::PRIVATE_KEY);
        $key = "o4rbXFDCzoqNZ68W";
        $iv = substr($key, 0, 16);
        if (strlen($json_bizContent) % 16) {
            $json_bizContent = str_pad($json_bizContent, strlen($json_bizContent) + 16 - strlen($json_bizContent) % 16, "\0");
        }
        $ret = array(
            'secretKey' => $this->publicEncrypt($key),
            'bizContent' => base64_encode(openssl_encrypt($json_bizContent, 'AES-128-CBC', $key, OPENSSL_NO_PADDING, $iv)),//加密
            'version' => "3.1",

        );
        $ret['sign'] = $this->privateEncrypt(md5($this->ASCII($ret)));//生成签名

        exit(json_encode($ret, JSON_UNESCAPED_SLASHES)); // 返回结果状态
    }

    //从省呗解密获取
    private function sb_get($secretKey, $bizContent)
    {
        $this->setResource(self::PUBLIC_KEY, self::PRIVATE_KEY);
        $key = $this->privateDecrypt($secretKey);
        $iv = substr($key, 0, 16);
        $json_bizContent = openssl_decrypt(base64_decode($bizContent), 'AES-128-CBC', $key, OPENSSL_NO_PADDING, $iv);//解密
        $json_bizContent = rtrim(rtrim($json_bizContent, chr(0)), chr(7));
        $bizContent = json_decode($json_bizContent, true);
        return $bizContent;
    }
    /**
     * 按照键值字典升序排列
     * @param array $params
     * @return string
     */
    private function ASCII($params = array()){
        if(!empty($params)){
            $p =  ksort($params);
            if($p){
                $str = '';
                foreach ($params as $k=>$val){
                    if($k=='bizContent'){
                        $str .=$k.'='.$val;
                    }else{
                        $str .= '&'.$k.'='.$val;
                    }
                }
                return $str;
            }
        }
        return '参数错误';
    }
}